var express = require('express')
const models = require("../../models");
const {success, error} = require("../../utils/message");
const checkPermission = require('../../middlewares/check-permission');
var router = express.Router()

// 品牌列表
router.get('/', checkPermission(), async function (req, res, next) {
    let brands = await models.Brand.findAll({
        include: [
            {
                model: models.Article,
                as: 'articles'
            }
        ],
        order: [
            ['createdAt', 'DESC'],
        ],
    })
    success(res, '查询成功', {brands})
})

// 新增品牌
router.post('/', checkPermission(),  async function (req, res, next) {
    const name = req.body.name
    const introduce = req.body.introduce

    if (!name) {
        return error(res, '请填写品牌名称')
    }

    if (!introduce) {
        return error(res, '请填写品牌介绍')
    }

    const brandName = await models.Brand.findOne({where: {name: name}})
    if (brandName) {
        return error(res, '该品牌已存在，请勿重复添加')
    }

    let brand = await models.Brand.create(req.body)
    success(res, '新增成功', {brand})
});

// 查询单条
router.get('/:id', checkPermission(),  async function (req, res, next) {
    const id = req.params.id

    const brand = await models.Brand.findByPk(id)
    if (!brand) {
        return error(res, '当前品牌不存在，无法修改')
    }

    success(res, '查询成功', {brand})
})

// 修改品牌
router.put('/:id', checkPermission(),  async function (req, res, next) {
    const id = req.params.id
    const name = req.body.name
    const introduce = req.body.introduce

    if (!name) {
        return error(res, '请填写广告名称')
    }

    if (!introduce) {
        return error(res, '请填写品牌介绍')
    }
    const brand = await models.Brand.findByPk(id)
    if (!brand) {
        return error(res, '当前品牌不存在，无法修改')
    }

    brand.update(req.body)
    success(res, '修改成功', {brand})
})

// 删除品牌
router.delete('/:id', checkPermission(),  async function (req, res, next) {
    const id = req.params.id

    const brand = await models.Brand.findOne({
        where: {id: id},
    })

    brand.destroy()
    success(res, '删除成功')
})

// 是否启用
router.patch('/:id/change_enable', checkPermission(),  async function (req, res, next) {
    console.log(req.body)
    const id = req.params.id
    const enable = req.body.enable

    const brand = await models.Brand.findByPk(id)
    if (!brand) {
        return error(res, '当前品牌不存在，无法修改')
    }

    brand.update({enable: !brand.enable})
    success(res, '修改成功')
})
module.exports = router
